package com.diyunapp.xilinapp.details;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.evaluations.EvaluationActivity;
import com.diyunapp.xilinapp.fragments.GoodDetailBuyRecordFragment;
import com.diyunapp.xilinapp.fragments.GoodDetailInfoFragment;
import com.diyunapp.xilinapp.login.LoginActivity;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.diyunapp.xilinapp.utils.FormatConfirm;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nuttysoft.nutand.utils.AppUtil;
import com.nuttysoft.nutand.utils.ViewUtil;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/6/20.
 */
public class GoodsDetailActivity extends StatusBarFragmentActivity implements View.OnClickListener {

    @Bind(R.id.gooddetail_goback_ib)
    ImageButton gooddetailGobackIb;
    @Bind(R.id.gooddetail_buycar_bt)
    ImageButton gooddetailBuycarBt;
    @Bind(R.id.gooddetail_buycar_tv)
    TextView gooddetailBuycarTv;
    @Bind(R.id.detail_convenientBanner)
    ConvenientBanner detailConvenientBanner;
    @Bind(R.id.goods_picture_tv)
    TextView goodsPictureTv;
    @Bind(R.id.detail_good_description_tv)
    TextView detailGoodDescriptionTv;
    @Bind(R.id.detail_good_price_tv)
    TextView detailGoodPriceTv;
    @Bind(R.id.detail_makret_price_tv)
    TextView detailMakretPriceTv;
    @Bind(R.id.xlb_money_tv)
    TextView xlbMoneyTv;
    @Bind(R.id.send_yunfei_tv)
    TextView sendYunfeiTv;
    @Bind(R.id.from_address_tv)
    TextView fromAddressTv;
    @Bind(R.id.detail_shop_iv)
    ImageView detailShopIv;
    @Bind(R.id.detail_shopname_tv)
    TextView detailShopnameTv;
    @Bind(R.id.detail_shopsave_state_tv)
    TextView detailShopsaveStateTv;
    @Bind(R.id.detail_shopaddress_tv)
    TextView detailShopaddressTv;
    @Bind(R.id.store_credit_ll)
    LinearLayout storeCreditLl;
    @Bind(R.id.detail_shopsale_numbers_tv)
    TextView detailShopsaleNumbersTv;
    @Bind(R.id.detail_shoplike_numbers_tv)
    TextView detailShoplikeNumbersTv;
    @Bind(R.id.detail_shopopen_time_tv)
    TextView detailShopopenTimeTv;
    @Bind(R.id.store_descrip_score_tv)
    TextView storeDescripScoreTv;
    @Bind(R.id.store_descrip_type_tv)
    TextView storeDescripTypeTv;
    @Bind(R.id.store_service_score_tv)
    TextView storeServiceScoreTv;
    @Bind(R.id.store_service_type_tv)
    TextView storeServiceTypeTv;
    @Bind(R.id.store_wuliu_score_tv)
    TextView storeWuliuScoreTv;
    @Bind(R.id.store_wuliu_type_tv)
    TextView storeWuliuTypeTv;
    @Bind(R.id.detail_shoptotalgoods_ll)
    LinearLayout detailShoptotalgoodsLl;
    @Bind(R.id.detail_gotoshop_ll)
    LinearLayout detailGotoshopLl;
    @Bind(R.id.good_evaluation_tv)
    TextView goodEvaluationTv;
    @Bind(R.id.good_evaluation_ll)
    LinearLayout goodEvaluationLl;
    @Bind(R.id.good_detail_rb)
    RadioButton goodDetailRb;
    @Bind(R.id.good_buyrecord_rb)
    RadioButton goodBuyrecordRb;
    @Bind(R.id.good_detail_fl)
    FrameLayout goodDetailFl;
    @Bind(R.id.connect_query_iv)
    ImageView connectQueryIv;
    @Bind(R.id.connect_query_tv)
    TextView connectQueryTv;
    @Bind(R.id.connect_query_ll)
    LinearLayout connectQueryLl;
    @Bind(R.id.save_good_iv)
    ImageView saveGoodIv;
    @Bind(R.id.save_good_tv)
    TextView saveGoodTv;
    @Bind(R.id.save_good_ll)
    LinearLayout saveGoodLl;
    @Bind(R.id.detail_buyatonce_bt)
    Button detailBuyatonceBt;
    @Bind(R.id.detail_addtobuycar_bt_bt)
    LinearLayout detailAddtobuycarBtBt;
    @Bind(R.id.ifhas_yhq_tv)
    TextView ifhasYhqTv;
    @Bind(R.id.goods_reserves_tv)
    TextView goodsReservesTv;
    @Bind(R.id.display_morecredit_ib)
    ImageButton displayMorecreditIb;
    @Bind(R.id.add_creditlist_childll1)
    LinearLayout addCreditlistChildll1;
    @Bind(R.id.add_creditlist_childll2)
    LinearLayout addCreditlistChildll2;
    @Bind(R.id.goods_houdong_tv)
    TextView goodsHoudongTv;

    private View headView;
    public static String good_id;
    private String goodsImages;
    private int picNumbers = 0;
    private String store_id;
    private String storeName;
    private int evaluationNum = 0;
    private List<String> picUrlList = new ArrayList<>();

    private Fragment goodDetailFrag;
    private Fragment goodBuyRecordFrag;
    private boolean ifgetGoods = false;

    private int creditnum = 0;
    private String storeQQ = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_detail_main_layout);
        ButterKnife.bind(this);
        headView = findViewById(R.id.gooddetail_menubar_inc);
        super.MenuWidget(headView);
        good_id = getIntent().getStringExtra("GoodId");
        initViews();
        getGoodsDetails();
        getBuyCarNum();
    }

    private void initViews() {

        detailShopsaveStateTv.setOnClickListener(this);
        connectQueryLl.setOnClickListener(this);
        saveGoodLl.setOnClickListener(this);
        detailBuyatonceBt.setOnClickListener(this);
        detailAddtobuycarBtBt.setOnClickListener(this);

        gooddetailGobackIb.setOnClickListener(this);
        gooddetailBuycarBt.setOnClickListener(this);
        goodEvaluationLl.setOnClickListener(this);
        detailShoptotalgoodsLl.setOnClickListener(this);
        detailGotoshopLl.setOnClickListener(this);

        displayMorecreditIb.setOnClickListener(this);

        goodDetailRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    selectFragment(1);
                }
            }
        });

        goodBuyrecordRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    selectFragment(2);
                }
            }
        });

        selectFragment(1);

    }


    @Override
    public void onClick(View v) {

        if ((!ifgetGoods) && (v.getId() != R.id.gooddetail_goback_ib)) {
            return;
        }

        switch (v.getId()) {
            case R.id.gooddetail_goback_ib:
                finish();
                break;
            case R.id.gooddetail_buycar_bt: //跳转到购物车页面
                if (MainActivity.myLogin.isLoginState()) {
                    Intent buycarInt = new Intent(this, BuyCarActivity.class);
                    startActivityForResult(buycarInt, 1);
                } else {
                    gotoLogin();
                }
                break;
            case R.id.detail_shopsave_state_tv:  //收藏店铺
                if (MainActivity.myLogin.isLoginState()) {
                    storeSaveSet();
                } else {
                    gotoLogin();
                }
                break;
            case R.id.save_good_ll: //收藏商品
                if (MainActivity.myLogin.isLoginState()) {
                    goodSaveSet();
                } else {
                    gotoLogin();
                }
                break;
            case R.id.detail_shoptotalgoods_ll:
                Intent allgoodsInt = new Intent(this, SearchResultActivity.class);
                allgoodsInt.putExtra("SearchKeyType", "keyword");
                allgoodsInt.putExtra("SearchKeyWord", "店铺搜索");
                allgoodsInt.putExtra("SearchStoreId", store_id);
                allgoodsInt.putExtra("SearchStoreName", storeName);
                startActivityForResult(allgoodsInt, 2);
                break;
            case R.id.detail_gotoshop_ll:
                Intent storeInt = new Intent(this, StoreActivity.class);
                storeInt.putExtra("StoreId", store_id);
                startActivityForResult(storeInt, 4);
                break;
            case R.id.good_evaluation_ll:
                if (evaluationNum > 0) {
                    Intent evaInt = new Intent(this, EvaluationActivity.class);
                    evaInt.putExtra("GoodId", good_id);
                    startActivity(evaInt);
                } else {
                    Toast.makeText(getApplicationContext(), "还没有人评价过此商品...", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.detail_buyatonce_bt:
            case R.id.detail_addtobuycar_bt_bt:
                if (MainActivity.myLogin.isLoginState()) {
                    Intent buyInt = new Intent(this, GoodBuyActivity.class);
                    buyInt.putExtra("GoodId", good_id);
                    buyInt.putExtra("GoodStore", storeName);
                    buyInt.putExtra("GoodImg", picUrlList.get(0));
                    startActivityForResult(buyInt, 3);
                } else {
                    gotoLogin();
                }
                break;
            case R.id.display_morecredit_ib:
                if (addCreditlistChildll2.isShown()) {
                    addCreditlistChildll2.setVisibility(View.GONE);
                } else {
                    addCreditlistChildll2.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.connect_query_ll:
                if(storeQQ==null || storeQQ.isEmpty()||storeQQ.equals("null")||storeQQ.equals("NULL"))
                {
                    Toast.makeText(getApplicationContext(),"亲，我还没有上线呢，再等我会儿吧~~",Toast.LENGTH_SHORT).show();
                }
                else {
                    FormatConfirm.startQQ(this, storeQQ);
                }
                break;
            default:
                break;
        }
    }

    private void gotoLogin() {
        Toast.makeText(getApplication(), "您还没有登录，请先登录！", Toast.LENGTH_SHORT).show();
        Intent logIntent = new Intent(this, LoginActivity.class);
        startActivityForResult(logIntent,10);
    }

    private void initPicture() {
        long turningTime = 5000;
        if (picUrlList.size() <= 1) {
            turningTime = 1200000; //如果图片张数小于2张，则将时间设置为20分钟
        }
        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
        detailConvenientBanner.setPages(
                new CBViewHolderCreator<LocalImageHolderView>() {
                    @Override
                    public LocalImageHolderView createHolder() {
                        return new LocalImageHolderView();
                    }
                }, picUrlList).startTurning(turningTime);
        //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
        //.setPageIndicator(bannerPoint);
        //设置指示器的方向
        //.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
        //设置翻页的效果，不需要翻页效果可用不设
        //.setPageTransformer(Transformer.DefaultTransformer);    集成特效之后会有白屏现象，新版已经分离，如果要集成特效的例子可以看Demo的点击响应。
        //convenientBanner.setManualPageable(false);//设置不能手动影响
    }

    public class LocalImageHolderView implements Holder<String> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            //imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            int screenWidth = AppUtil.getDisplayMetrics(context).heightPixels;
            int targetPicHeight = (int) ViewUtil.dip2px(context, 180);
            Picasso.with(context)
                    .load(data)//int) width * 400 / 1392
                    //.resize((int) width * 400 / 1392, targetPicHeight)
                    //.centerCrop()
                    //.centerInside()
                    .config(Bitmap.Config.RGB_565)
                    .error(R.drawable.list_default)
                    .placeholder(R.drawable.list_default)
                    .into(imageView);

            int currentpic = position + 1;
            goodsPictureTv.setText(currentpic + "/" + picNumbers);
        }
    }

    private void setNetPicture() {
        //设置图片
        String tempUrlxiegang = goodsImages.replace("\\", "");

        String subUrl = goodsImages;
        for (; ; ) {
            int douhaoIndex = subUrl.indexOf(",");
            if (douhaoIndex < 0) {
                picUrlList.add(subUrl);
                picNumbers = picUrlList.size();
                break;
            }
            String urlComplete = subUrl.substring(0, douhaoIndex);
            picUrlList.add(urlComplete);
            String tempsubUrl = subUrl.substring(douhaoIndex + 1, subUrl.length());
            subUrl = tempsubUrl;
        }

        initPicture();
    }


    private void getGoodsDetails() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=goods_detail&goods_id=" + good_id + "&member_id=" + MainActivity.myLogin.getMemberid();
        Log.i("zhangxiaoxidebug", "detail url =" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getApplicationContext(), "查询失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }


                    @Override
                    public void onStart() {

                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "detail_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");
                            JSONObject jsObjectGoodsinfo = jsObjectDatas.getJSONObject("goods_info");
                            String goodsName = jsObjectGoodsinfo.getString("goods_name");
                            detailGoodDescriptionTv.setText(goodsName);
                            goodsImages = jsObjectDatas.getString("goods_image");
                            setNetPicture();
                            String goodPrice = jsObjectGoodsinfo.getString("goods_price");
                            String PriceText = "";
                            if (jsObjectGoodsinfo.has("promotion_price")) {
                                String promotion_price = jsObjectGoodsinfo.getString("promotion_price");
                                PriceText = PriceText + "￥" + promotion_price;
                                if (jsObjectGoodsinfo.has("title")) {
                                    PriceText = PriceText + "(" + jsObjectGoodsinfo.getString("title");
                                    if (jsObjectGoodsinfo.has("upper_limit")) {
                                        int upper_limit = FormatConfirm.stringToInt(jsObjectGoodsinfo.getString("upper_limit"));
                                        if (upper_limit > 0) {
                                            PriceText = PriceText + "，限购" + upper_limit + "件";
                                        }
                                    }
                                   else if (jsObjectGoodsinfo.has("down_price")) {
                                        float  down_price = FormatConfirm.stringToFloat(jsObjectGoodsinfo.getString("down_price"));
                                        if (down_price > 0) {
                                            PriceText = PriceText + "，直降" + down_price + "元";
                                            if(jsObjectGoodsinfo.has("lower_limit"))
                                            {
                                                int lower_limit = FormatConfirm.stringToInt(jsObjectGoodsinfo.getString("lower_limit"));
                                                if (lower_limit > 0) {
                                                    PriceText = PriceText + "，最低" + lower_limit + "件起";
                                                }
                                            }
                                        }
                                    }
                                    PriceText = PriceText + ")";
                                }

                                PriceText = PriceText + "  (原售价￥" + goodPrice + ")";
                                SpannableString goodPriceSp = new SpannableString(PriceText);
                                int indexTitle = PriceText.indexOf("(");
                                int indexOragin = PriceText.indexOf("  (原售价");

                                //设置字体大小
                                goodPriceSp.setSpan(new AbsoluteSizeSpan(12, true), indexTitle, PriceText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                                //设置字体颜色
                                goodPriceSp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.grey_old_price)), indexOragin, PriceText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                detailGoodPriceTv.setText(goodPriceSp);
                            } else {
                                detailGoodPriceTv.setText("￥" + goodPrice);
                            }
                            String marketPrice = jsObjectGoodsinfo.getString("goods_marketprice");
                            detailMakretPriceTv.setText("市场价：￥" + marketPrice);
                            //设置中划线
                            detailMakretPriceTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                            //商品库存
                            String goods_storage = jsObjectGoodsinfo.getString("goods_storage");
                            goodsReservesTv.setText("库存: " + goods_storage);

                            //商品收藏状态处理
                            int good_is_fav = jsObjectGoodsinfo.getInt("is_fav");
                            if (good_is_fav > 0) {
                                saveGoodIv.setImageDrawable(getResources().getDrawable(R.drawable.xiacangon));
                                saveGoodTv.setText("取消");
                            } else {
                                saveGoodIv.setImageDrawable(getResources().getDrawable(R.drawable.xiacangoff));
                                saveGoodTv.setText("收藏");
                            }

                            //店铺活动模块
                            String mansongInfo = jsObjectDatas.getString("mansong_info");
                            if (mansongInfo.contains("mansong_name")) {
                                JSONObject jsObjectMansong = new JSONObject(mansongInfo);
                                String mansongName = jsObjectMansong.getString("mansong_name");
                                goodsHoudongTv.setVisibility(View.VISIBLE);
                                goodsHoudongTv.setText("活动: "+mansongName);
                            }
                            else {
                                goodsHoudongTv.setVisibility(View.GONE);
                            }

                            //店铺模块信息设置
                            JSONObject jsObjectStore = jsObjectDatas.getJSONObject("store_info");
                            store_id = jsObjectStore.getString("store_id");
                            storeName = jsObjectStore.getString("store_name");
                            detailShopnameTv.setText(storeName);
                            String storeAddress = jsObjectStore.getString("store_address");
                            detailShopaddressTv.setText(storeAddress);
                            String storeImg = jsObjectStore.getString("avatar");
                            ImageLoader.getInstance().displayImage(storeImg, detailShopIv, FormatConfirm.getOption());
                            storeQQ = jsObjectStore.getString("store_qq");

                            int is_fav = jsObjectStore.getInt("is_fav");
                            if (is_fav > 0) {
                                detailShopsaveStateTv.setText("已收藏");
                                detailShopsaveStateTv.setTextColor(getResources().getColor(R.color.domain_orange));
                            } else {
                                detailShopsaveStateTv.setText("收藏");
                                detailShopsaveStateTv.setTextColor(getResources().getColor(R.color.grey_old_price));
                            }

                            //信用度
                            int creditValue = FormatConfirm.stringToInt(jsObjectStore.getString("store_credit"));
                            setStoreCredit(creditValue);

                            //店铺评分
                            String store_desccredit = jsObjectStore.getString("store_desccredit");
                            String store_servicecredit = jsObjectStore.getString("store_servicecredit");
                            String store_deliverycredit = jsObjectStore.getString("store_deliverycredit");
                            storeDescripScoreTv.setText(store_desccredit);
                            storeServiceScoreTv.setText(store_servicecredit);
                            storeWuliuScoreTv.setText(store_deliverycredit);
                            String desccredit_type = jsObjectStore.getString("store_desccredit_text");
                            setStoreScore(desccredit_type, storeDescripTypeTv);
                            String servicecredit_type = jsObjectStore.getString("store_servicecredit_text");
                            setStoreScore(servicecredit_type, storeServiceTypeTv);
                            String deliverycredit_type = jsObjectStore.getString("store_deliverycredit_text");
                            setStoreScore(deliverycredit_type, storeWuliuTypeTv);

                            //商户保证部分内容
                            creditnum = 0;
                            addCreditlistChildll1.removeAllViews();
                            addCreditlistChildll2.removeAllViews();
                            String store_shiti = jsObjectStore.getString("store_shiti");
                            setPromiseInfo(0, store_shiti);
                            String store_qtian = jsObjectStore.getString("store_qtian");
                            setPromiseInfo(1, store_qtian);
                            String store_zhping = jsObjectStore.getString("store_zhping");
                            setPromiseInfo(2, store_zhping);
                            String store_erxiaoshi = jsObjectStore.getString("store_erxiaoshi");
                            setPromiseInfo(3, store_erxiaoshi);
                            String store_tuihuo = jsObjectStore.getString("store_tuihuo");
                            setPromiseInfo(4, store_tuihuo);
                            String store_shiyong = jsObjectStore.getString("store_shiyong");
                            setPromiseInfo(5, store_shiyong);
                            String store_xiaoxie = jsObjectStore.getString("store_xiaoxie");
                            setPromiseInfo(6, store_xiaoxie);
                            String store_huodaofk = jsObjectStore.getString("store_huodaofk");
                            setPromiseInfo(7, store_huodaofk);

                            Log.i("zhangxiaoxidebug", "creditnum=" + creditnum);
                            if (creditnum < 3) {
                                displayMorecreditIb.setVisibility(View.GONE);
                            }

                            //希霖币抵扣
                            float xlbMoney = FormatConfirm.stringToFloat(jsObjectStore.getString("xlbdk"));
                            if (xlbMoney > 0) {
                                xlbMoneyTv.setVisibility(View.VISIBLE);
                                String xlbStr = "希霖币可抵: " + xlbMoney + "元";
                                SpannableString xlbSpan = new SpannableString(xlbStr);
                                xlbSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.grey_good_evaluate)), xlbStr.indexOf(" "), xlbStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                xlbMoneyTv.setText(xlbSpan);
                            } else {
                                xlbMoneyTv.setVisibility(View.INVISIBLE);
                            }

                            //是否有优惠券
                            int hasYhq = jsObjectStore.getInt("voucher");
                            if (hasYhq > 0) {
                                ifhasYhqTv.setVisibility(View.VISIBLE);
                            } else {
                                ifhasYhqTv.setVisibility(View.INVISIBLE);
                            }

                            //运费+发货地址
                            String yunfei = jsObjectStore.getString("yunfei");
                            String yunfeiStr = "运费: " + yunfei + " 元起";
                            SpannableString yunfeiSpan = new SpannableString(yunfeiStr);
                            yunfeiSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.grey_good_evaluate)), yunfeiStr.indexOf(" "), yunfeiStr.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            sendYunfeiTv.setText(yunfeiSpan);
                            fromAddressTv.setText(jsObjectStore.getString("area_info"));

                            //关注人数
                            String goods_collect = jsObjectGoodsinfo.getString("goods_collect");
                            float collectTemp = FormatConfirm.stringToFloat(goods_collect);
                            int indexoff = 1;
                            if (collectTemp > 10000) {
                                goods_collect = FormatConfirm.moneyTwodot(String.valueOf(collectTemp / 10000)) + "万人";
                                indexoff = 2;
                            } else {
                                goods_collect += "人";
                            }

                            SpannableString collectSpan = new SpannableString(goods_collect);
                            collectSpan.setSpan(new AbsoluteSizeSpan(17), goods_collect.length() - indexoff, goods_collect.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            detailShoplikeNumbersTv.setText(collectSpan);

                            //开店时长
                            String timeStr = jsObjectStore.getInt("kdsc") + "年";
                            SpannableString timeSpan = new SpannableString(timeStr);
                            timeSpan.setSpan(new AbsoluteSizeSpan(17), timeStr.indexOf("年"), goods_collect.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            detailShopopenTimeTv.setText(timeSpan);

                            //此商品总销量
                            String goods_salenum = jsObjectGoodsinfo.getString("goods_salenum");
                            detailShopsaleNumbersTv.setText(goods_salenum);
                            goodBuyrecordRb.setText("购买记录（" + goods_salenum + "）");

                            //商品评价
                            String goods_evaluation = jsObjectGoodsinfo.getString("evaluation_count");
                            evaluationNum = FormatConfirm.stringToInt(goods_evaluation);
                            String goods_evaluation_info = "（ " + goods_evaluation + " 人评价）";
                            SpannableString msp_canuse = new SpannableString(goods_evaluation_info);
                            //设置字体颜色eb534a
                            msp_canuse.setSpan(new ForegroundColorSpan(0xFFEB534A), goods_evaluation_info.indexOf("（") + 1, goods_evaluation_info.indexOf("人"), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            goodEvaluationTv.setText(msp_canuse);

                            ifgetGoods = true;

                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "读取数据失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void setPromiseInfo(int type, String value) {

        if (!value.equals("1")) {
            return;
        }

        ImageView tempIv = new ImageView(this);
        TextView textView = new TextView(this);
        textView.setTextColor(getResources().getColor(R.color.grey_text_more));
        textView.setTextSize(12);
        View sepView1 = new View(this);
        sepView1.setLayoutParams(new LinearLayout.LayoutParams(5, ViewGroup.LayoutParams.MATCH_PARENT));

        switch (type) {
            case 0:
                tempIv.setImageResource(R.drawable.shiti);
                textView.setText("实体认证");
                break;
            case 1:
                tempIv.setImageResource(R.drawable.pai);
                textView.setText("实物拍摄");
                break;
            case 2:
                tempIv.setImageResource(R.drawable.zheng);
                textView.setText("正品保障");
                break;
            case 3:
                tempIv.setImageResource(R.drawable.er);
                textView.setText("2小时内发货");
                break;
            case 4:
                tempIv.setImageResource(R.drawable.tui48);
                textView.setText("退货承诺");
                break;
            case 5:
                tempIv.setImageResource(R.drawable.trytouse);
                textView.setText("试用中心");
                break;
            case 6:
                tempIv.setImageResource(R.drawable.chengxin);
                textView.setText("消费者保障");
                break;
            case 7:
                tempIv.setImageResource(R.drawable.daofu);
                textView.setText("货到付款");
                break;
            default:
                break;

        }

        if (creditnum > 2) {
            View sepView3 = new View(this);
            sepView3.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 10));
            LinearLayout tempLl = new LinearLayout(this);
            tempLl.setGravity(Gravity.CENTER_VERTICAL);
            tempLl.setOrientation(LinearLayout.HORIZONTAL);
            tempLl.addView(tempIv);
            tempLl.addView(sepView1);
            tempLl.addView(textView);
            addCreditlistChildll2.addView(sepView3);
            addCreditlistChildll2.addView(tempLl);
            displayMorecreditIb.setVisibility(View.VISIBLE);
        } else {
            View sepView2 = new View(this);
            sepView2.setLayoutParams(new LinearLayout.LayoutParams(25, ViewGroup.LayoutParams.MATCH_PARENT));
            addCreditlistChildll1.addView(tempIv);
            addCreditlistChildll1.addView(sepView1);
            addCreditlistChildll1.addView(textView);
            addCreditlistChildll1.addView(sepView2);
            displayMorecreditIb.setVisibility(View.INVISIBLE);
        }
        creditnum++;
    }

    private void setStoreScore(String desccredit_type, TextView storeDescripTypeTv) {

        if (desccredit_type.contains("低")) {
            storeDescripTypeTv.setBackground(getResources().getDrawable(R.drawable.circle_cornor_green_background));
            storeDescripTypeTv.setText("低");
        } else if (desccredit_type.contains("高")) {
            storeDescripTypeTv.setBackground(getResources().getDrawable(R.drawable.circle_cornor_red_background));
            storeDescripTypeTv.setText("高");
        } else {
            storeDescripTypeTv.setBackground(getResources().getDrawable(R.drawable.circle_cornor_red_background));
            storeDescripTypeTv.setText("平");
        }
    }

    private void setStoreCredit(int creditint) {
        storeCreditLl.removeAllViews();
        LinearLayout.LayoutParams myParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
        myParams.setMargins(0, 0, 3, 0);
        for (int i = 0; i < creditint; i++) {
            ImageView creditHeart = new ImageView(this);
            creditHeart.setImageResource(R.drawable.cang);
            storeCreditLl.addView(creditHeart, myParams);
            /*View blankView = new View(this);
            blankView.setLayoutParams(new LinearLayout.LayoutParams(3,LinearLayout.LayoutParams.MATCH_PARENT));
            storeCreditLl.addView(blankView);*/
        }
    }


    private void goodSaveSet() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=goods_fav&goods_id=" + good_id + "&member_id=" + MainActivity.myLogin.getMemberid();
        Log.i("zhangxiaoxidebug", "goodSaveSet url =" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getApplicationContext(), "收藏操作失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "save_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");
                            int is_fav = jsObjectDatas.getInt("is_fav");
                            if (is_fav > 0) {
                                saveGoodIv.setImageDrawable(getResources().getDrawable(R.drawable.xiacangon));
                                saveGoodTv.setText("取消");
                            } else {
                                saveGoodIv.setImageDrawable(getResources().getDrawable(R.drawable.xiacangoff));
                                saveGoodTv.setText("收藏");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "收藏操作失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void storeSaveSet() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=store_fav&store_id=" + store_id + "&member_id=" + MainActivity.myLogin.getMemberid();
        Log.i("zhangxiaoxidebug", "storeSaveSet url =" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getApplicationContext(), "收藏操作失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }


                    @Override
                    public void onStart() {

                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "save_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");
                            int is_fav = jsObjectDatas.getInt("is_fav");
                            if (is_fav > 0) {
                                detailShopsaveStateTv.setText("已收藏");
                                detailShopsaveStateTv.setTextColor(getResources().getColor(R.color.domain_orange));

                            } else {
                                detailShopsaveStateTv.setText("收藏");
                                detailShopsaveStateTv.setTextColor(getResources().getColor(R.color.grey_old_price));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "收藏操作失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    public void getBuyCarNum() {
        if (!MainActivity.myLogin.isLoginState()) {
            return;
        }
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=cart_num&member_id=" + MainActivity.myLogin.getMemberid();
        Log.i("zhangxiaoxidebug", "getBuyCarNum url= " + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "buycar num info=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            JSONObject jsObjectNum = resultObject.getJSONObject("data");
                            String buycarNum = jsObjectNum.getString("num");
                            gooddetailBuycarTv.setText(buycarNum);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });
    }

    private void selectFragment(int flagInt) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);
        switch (flagInt) {
            case 1:
                if (goodDetailFrag == null) {
                    goodDetailFrag = new GoodDetailInfoFragment();
                    transaction.add(R.id.good_detail_fl, goodDetailFrag);
                } else {
                    transaction.show(goodDetailFrag);
                }
                break;
            case 2:
                if (goodBuyRecordFrag == null) {
                    goodBuyRecordFrag = new GoodDetailBuyRecordFragment();
                    transaction.add(R.id.good_detail_fl, goodBuyRecordFrag);
                } else {
                    transaction.show(goodBuyRecordFrag);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (goodDetailFrag != null) {
            transaction.hide(goodDetailFrag);
        }
        if (goodBuyRecordFrag != null) {
            transaction.hide(goodBuyRecordFrag);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //所有点击返回后，都重新刷新购物车数量
        getGoodsDetails();
        getBuyCarNum();
        super.onActivityResult(requestCode, resultCode, data);
    }
}
